package com.bestcem.xm.deliver.grpc.service;

import com.bestcem.xm.deliver.service.DeliverDeliverService;
import com.bestcem.xm.tinyurl.grpc.v1.services.GetShortLinkRequest;
import com.bestcem.xm.tinyurl.grpc.v1.services.GetShortLinkResponse;
import com.bestcem.xm.tinyurl.grpc.v1.services.ShortLinkServiceGrpc;
import io.grpc.stub.StreamObserver;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import zhongyan.xm.base.v1.Base;

@GrpcService
@Slf4j
@RequiredArgsConstructor
public class ShortLinkGrpcService extends ShortLinkServiceGrpc.ShortLinkServiceImplBase {
    private static final Base.Status SUCCESS_STATUS = Base.Status.newBuilder().setCode(Base.Code.OK).build();
    private static final Base.Status FAIL_STATUS = Base.Status.newBuilder().setCode(Base.Code.ERROR).build();

    private @NonNull DeliverDeliverService service;


    @Override
    public void getShortLink(GetShortLinkRequest request, StreamObserver<GetShortLinkResponse> responseObserver) {
        GetShortLinkResponse.Builder result = GetShortLinkResponse.newBuilder();
        String link = request.getLink();
        try {
            String shortUrl = service.aioConvertShortUrl(link, null);
            result.setStatus(SUCCESS_STATUS);
            result.setShortLink(shortUrl);
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
        } catch (Exception e) {
            log.error("Exception e, ", e);
            result.setStatus(FAIL_STATUS);
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
        }
    }
}
